﻿using HomagChina.Basic.CCT.Db.CCT_Db;
using HomagChina.Basic.CCT.Db.Printer_Db;
using HomagChina.Basic.CCT.PLC;
using Serilog;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Untilly;
using Globle = Utility.Globle;

namespace Proxy
{
    public class InfeedHandle
    {
        private SearchInfoHandle Handle_Search;
        private InsertInfoHandle Handle_Insert;
        private ModifyInfoHandle Handle_Modify;
        private PlcHandle Handle_Plc;

        public InfeedHandle()
        {
            Handle_Search = new SearchInfoHandle();
            Handle_Insert = new InsertInfoHandle();
            Handle_Modify = new ModifyInfoHandle();
            Handle_Plc = new PlcHandle();
            Task.Factory.StartNew(() => DealWithDataReq());
            Task.Factory.StartNew(() => DealWithPosReq());
            Task.Factory.StartNew(() => DealWithLabelReq());
            Task.Factory.StartNew(() => DealWithRePosReq());
            //Task.Factory.StartNew(() => DealWithReLabelALLReq());
        }

        /// <summary>
        /// 数据请求
        /// </summary>
        private void DealWithDataReq()
        {
            View_LabelTaskDetail view_LabelTaskDetail = new View_LabelTaskDetail();
            T_Nesting_LabelTask t_Nesting_LabelTask = new T_Nesting_LabelTask();
            var log = SerilogHandle.Logger_Production;
            do
            {
            Start:
                try
                {
                    Thread.Sleep(2000);
                    if (Globle.isInfeedAreaActive && !Globle.isRunEmptyActive)
                    {
                        Handle_Plc.Write(PlcItems.Item_Upper_Ready, true);
                        var DataReq = (bool)Handle_Plc.Read(PlcItems.Item_PLC_ReqInfo, "Bool");
                        if (!DataReq)
                        {
                            goto Start;
                        }

                        view_LabelTaskDetail = Handle_Search.GetLabelTaskDetail((int)EnumOfPartState.等待执行);
                        if (view_LabelTaskDetail == null)
                        {
                            goto Start;
                        }
                        log.Information("收到PLC数据请求");

                        //发送Mpr文件名
                        Handle_Plc.Write(PlcItems.Item_Upper_Mpr, view_LabelTaskDetail.MprName);
                        log.Information("发送Mpr信息：" + view_LabelTaskDetail.MprName);

                        T_Nesting_BoardInfo t_NestingBoardInfo = Handle_Search.GetNestingBoardInfo(view_LabelTaskDetail.MprName);
                        if (t_NestingBoardInfo == null) { goto Start; }
                        else
                        {
                            Handle_Plc.Write(PlcItems.Item_Upper_LabelSum, t_NestingBoardInfo.PartsAmount);
                        }
                        Handle_Modify.ModifyLabelPrintState_Board((int)EnumOfBoardOrBatchState.等待执行, (int)EnumOfBoardOrBatchState.正在执行, log);
                        goto Start;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    goto Start;
                }
            } while (true);
        }

        /// <summary>
        /// 位置请求
        /// </summary>
        private void DealWithPosReq()
        {
            View_LabelTaskDetail view_LabelTaskDetail = new View_LabelTaskDetail();
            T_Nesting_LabelTask t_Nesting_LabelTask = new T_Nesting_LabelTask();
            View_LabelTaskDetail view_NextLabelTaskDetail = new View_LabelTaskDetail();
            var log = SerilogHandle.Logger_Production;
            do
            {
            Start:
                try
                {
                    Thread.Sleep(2000);
                    if (Globle.isInfeedAreaActive && !Globle.isRunEmptyActive)
                    {
                        var PosReq = (bool)Handle_Plc.Read(PlcItems.Item_PLC_ReqPos, "Bool");
                        if (!PosReq)
                        {
                            goto Start;
                        }

                        view_LabelTaskDetail = Handle_Search.GetLabelTaskDetail((int)EnumOfPartState.等待执行);
                        if (view_LabelTaskDetail == null)
                        {
                            goto Start;
                        }
                        log.Information("收到PLC位置信息请求 :" + view_LabelTaskDetail.Reference);

                        if (view_LabelTaskDetail.OffcutFiag == 1)
                        {
                            log.Information("余料！");
                            Handle_Modify.ModifyLabelPrintState_Part((int)EnumOfPartState.等待执行, (int)EnumOfPartState.已发送出标完成, log);
                            //Tell plc , this is offcut
                            Handle_Plc.Write(PlcItems.Item_Upper_Offcut, true);
                            T_Nesting_BoardInfo t_NestingBoardInfo = Handle_Search.GetNestingBoardInfo(view_LabelTaskDetail.MprName);
                            if (view_LabelTaskDetail.Number.Equals(t_NestingBoardInfo.PartsAmount))
                            {
                                //说明该大板的贴标任务已完成
                                Handle_Modify.ModifyLabelPrintState_Board((int)EnumOfBoardOrBatchState.正在执行, (int)EnumOfBoardOrBatchState.完成, log);
                                Handle_Plc.Write(PlcItems.Item_Upper_AllDone, true);
                                log.Information(view_LabelTaskDetail.MprName + "该板件贴标完成，发送AllDone信号给PLC");
                            }
                            else
                            {
                                log.Information(view_LabelTaskDetail.MprName + "继续执行贴标任务。");
                            }
                            goto Start;
                        }
                        else
                        {
                            float? LabelPos_X = 0;
                            float? LabelPos_Y = 0;
                            switch (view_LabelTaskDetail.Rotation)
                            {
                                case 0:
                                    LabelPos_X = view_LabelTaskDetail.PartPos_X - (view_LabelTaskDetail.PartLength / 2);
                                    LabelPos_Y = view_LabelTaskDetail.PartPos_Y - (view_LabelTaskDetail.PartWidth / 2);
                                    break;
                                case 90:
                                    LabelPos_X = view_LabelTaskDetail.PartPos_X - (view_LabelTaskDetail.PartWidth / 2);
                                    LabelPos_Y = view_LabelTaskDetail.BoardWidth - (view_LabelTaskDetail.PartPos_Y + (view_LabelTaskDetail.PartLength / 2));
                                    break;
                                case 180:
                                    LabelPos_X = view_LabelTaskDetail.PartPos_X - (view_LabelTaskDetail.PartLength / 2);
                                    LabelPos_Y = view_LabelTaskDetail.BoardWidth - (view_LabelTaskDetail.PartPos_Y - (view_LabelTaskDetail.PartWidth / 2));
                                    break;
                                case 270:
                                    LabelPos_X = view_LabelTaskDetail.PartPos_X + (view_LabelTaskDetail.PartWidth / 2);
                                    LabelPos_Y = view_LabelTaskDetail.BoardWidth - (view_LabelTaskDetail.PartPos_Y - (view_LabelTaskDetail.PartLength / 2));
                                    break;
                            }
                            Handle_Plc.Write(PlcItems.Item_Upper_XPos, (int)LabelPos_X);
                            Handle_Plc.Write(PlcItems.Item_Upper_YPos, (int)LabelPos_Y);
                            log.Information("位置信息发送完成");
                            Handle_Modify.ModifyLabelPrintState_Part((int)EnumOfPartState.等待执行, (int)EnumOfPartState.已发送位置信息, log);
                        }
                        goto Start;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    goto Start;
                }
            } while (true);
        }

        /// <summary>
        /// 贴标请求
        /// </summary>
        private void DealWithLabelReq()
        {
            View_LabelTaskDetail view_LabelTaskDetail = new View_LabelTaskDetail();
            View_LabelTaskDetail view_NextLabelTaskDetail = new View_LabelTaskDetail();
            T_Nesting_LabelTask t_Nesting_LabelTask = new T_Nesting_LabelTask();
            var log = SerilogHandle.Logger_Production;
            do
            {
            Start:
                try
                {
                    Thread.Sleep(2000);
                    if (Globle.isInfeedAreaActive && !Globle.isRunEmptyActive)
                    {
                        var LabelPrintReq = (bool)Handle_Plc.Read(PlcItems.Item_PLC_ReqLabel, "Bool");
                        if (!LabelPrintReq)
                        {
                            goto Start;
                        }

                        view_LabelTaskDetail = Handle_Search.GetLabelTaskDetail((int)EnumOfPartState.已发送位置信息);
                        if (view_LabelTaskDetail == null)
                        {
                            goto Start;
                        }

                        var pnxInfo = Handle_Search.GetPnxInfo(view_LabelTaskDetail.BatchId, int.Parse(view_LabelTaskDetail.PartId));
                        //调用打印机打印标签
                        if (!new HomagChina.Basic.CCT.Tools.PrinterHelper().CreatePrinterJob("PartLabel", "TOSHIBA B-EX4T2 (300 dpi)", pnxInfo.Id))
                        {
                            log.Information(view_LabelTaskDetail.BatchId + "-" + view_LabelTaskDetail.PartId + ": 生产打印任务失败");
                            goto Start;
                        }

                        Handle_Plc.Write(PlcItems.Item_Upper_LabelFin, true);
                        t_Nesting_LabelTask.State = (int)EnumOfPartState.已发送出标完成;
                        Handle_Modify.ModifyLabelPrintState_Part((int)EnumOfPartState.已发送位置信息, (int)EnumOfPartState.已发送出标完成, log);
                        /*
                                对比当前的贴标任务的number是否与BoardInfo内PartsAmount相同，相同则说明该Board的贴标任务以完成
                            */
                        T_Nesting_BoardInfo t_NestingBoardInfo = Handle_Search.GetNestingBoardInfo(view_LabelTaskDetail.MprName);
                        if (view_LabelTaskDetail.Number.Equals(t_NestingBoardInfo.PartsAmount))//说明该大板的贴标任务已完成
                        {
                            log.Information(view_LabelTaskDetail.MprName + "：该板件贴标完成");
                            Handle_Plc.Write(PlcItems.Item_Upper_AllDone, true);
                            Handle_Modify.ModifyLabelPrintState_Board((int)EnumOfBoardOrBatchState.正在执行, (int)EnumOfBoardOrBatchState.完成, log);
                        }
                        else
                        {
                            log.Information(view_LabelTaskDetail.MprName + "：等待继续贴标");
                        }
                        goto Start;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    goto Start;
                }
            } while (true);
        }

        /// <summary>
        /// 单位置重新请求贴标
        /// </summary>
        private void DealWithRePosReq()
        {
            View_LabelTaskDetail view_LabelTaskDetail = new View_LabelTaskDetail();
            T_Nesting_LabelTask t_Nesting_LabelTask = new T_Nesting_LabelTask();
            var log = SerilogHandle.Logger_Production;
            do
            {
            Start:
                try
                {
                    Thread.Sleep(2000);
                    if (Globle.isInfeedAreaActive && !Globle.isRunEmptyActive)
                    {
                        var PosReq = (bool)Handle_Plc.Read(PlcItems.Item_PLC_ReqPosAgain, "Bool");
                        if (!PosReq)
                        {
                            goto Start;
                        }

                        view_LabelTaskDetail = Handle_Search.GetLabelTaskForRePrint();
                        if (view_LabelTaskDetail == null)
                        {
                            goto Start;
                        }
                        log.Information(view_LabelTaskDetail.MprName + "- Number:" + view_LabelTaskDetail.Number + "：接收到单标签重复打印请求");
                        float? LabelPos_X = 0;
                        float? LabelPos_Y = 0;
                        switch (view_LabelTaskDetail.Rotation)
                        {
                            case 0:
                                LabelPos_X = view_LabelTaskDetail.PartPos_X - (view_LabelTaskDetail.PartLength / 2);
                                LabelPos_Y = view_LabelTaskDetail.PartPos_Y - (view_LabelTaskDetail.PartWidth / 2);
                                break;
                            case 90:
                                LabelPos_X = view_LabelTaskDetail.PartPos_X - (view_LabelTaskDetail.PartWidth / 2);
                                LabelPos_Y = view_LabelTaskDetail.BoardWidth - (view_LabelTaskDetail.PartPos_Y + (view_LabelTaskDetail.PartLength / 2));
                                break;
                            case 180:
                                LabelPos_X = view_LabelTaskDetail.PartPos_X - (view_LabelTaskDetail.PartLength / 2);
                                LabelPos_Y = view_LabelTaskDetail.BoardWidth - (view_LabelTaskDetail.PartPos_Y - (view_LabelTaskDetail.PartWidth / 2));
                                break;
                            case 270:
                                LabelPos_X = view_LabelTaskDetail.PartPos_X + (view_LabelTaskDetail.PartWidth / 2);
                                LabelPos_Y = view_LabelTaskDetail.BoardWidth - (view_LabelTaskDetail.PartPos_Y - (view_LabelTaskDetail.PartLength / 2));
                                break;
                            default:
                                break;
                        }
                        log.Information("坐标计算完成");
                        Handle_Plc.Write(PlcItems.Item_Upper_XPos, (int)LabelPos_X);
                        Handle_Plc.Write(PlcItems.Item_Upper_YPos, (int)LabelPos_Y);
                        Handle_Modify.ModifyLabelPrintStateForRePrint(view_LabelTaskDetail.TaskId, (int)EnumOfPartState.已发送位置信息, log);
                        goto Start;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    goto Start;
                }
            } while (true);
        }

        /// <summary>
        /// 整板重复贴标请求
        /// </summary>
        private void DealWithReLabelALLReq()
        {
            T_Nesting_BoardInfo t_NestingBoardInfo = new T_Nesting_BoardInfo();
            T_Nesting_LabelTask t_Nesting_LabelTask = new T_Nesting_LabelTask();
            var log = SerilogHandle.Logger_DealWithReLabelALLReq;
            do
            {
            Start:
                try
                {
                    if (Globle.isInfeedAreaActive && !Globle.isRunEmptyActive)
                    {
                        Thread.Sleep(1000);
                        //看PLC是否有数据请求信号发过来
                        var DataReq = (bool)Handle_Plc.Read(PlcItems.Item_PLC_ReqInfoAgain, "Bool");
                        if (!DataReq)
                        {
                            goto Start;
                        }
                        //查看不是等待执行状态下的最新执行的板子
                        t_NestingBoardInfo = Handle_Search.GetLatestLabelTaskDetail_Board();
                        if (t_NestingBoardInfo == null)
                        {
                            goto Start;
                        }
                        log.Information(t_NestingBoardInfo.MprName + "：接收到整板重复打印请求，");

                        //发送Mpr文件名
                        Handle_Plc.Write(PlcItems.Item_Upper_Mpr, t_NestingBoardInfo.MprName);
                        t_Nesting_LabelTask.State = (int)EnumOfPartState.已发送数据;
                        Handle_Modify.ModifyState_Board(t_NestingBoardInfo.BoardId, (int)EnumOfBoardOrBatchState.正在执行);
                        goto Start;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    goto Start;
                }
            } while (true);
        }
    }
}